package com.xiyoukt.springboot.controller;

import com.alibaba.fastjson.JSONObject;
import com.xiyoukt.springboot.Goods;
import com.xiyoukt.springboot.Result;
import com.xiyoukt.springboot.User;
import com.xiyoukt.springboot.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@RestController
//@Controller
public class UserController {

    private static Logger log = LoggerFactory.getLogger(UserController.class);

    // 应该使用POST的请求方式
    @GetMapping("registry")
    public Result<Boolean> registry(@Validated(User.Registry.class) User user, BindingResult bindingResult){
        ResultUtil<Boolean> resultUtil = new ResultUtil<>();
        if(bindingResult.hasErrors()){
            return resultUtil.fail(201, bindingResult.getFieldError().getField()
                    + " : "+ bindingResult.getFieldError().getDefaultMessage());
        }

        return resultUtil.success(Boolean.TRUE);
    }

    // 应该使用POST的请求方式
    @GetMapping("login")
    public Result<Boolean> login(@Validated(User.Login.class) User user, BindingResult bindingResult){
        ResultUtil<Boolean> resultUtil = new ResultUtil<>();
        if(bindingResult.hasErrors()){
            return resultUtil.fail(201, bindingResult.getFieldError().getField()
                    + " : "+ bindingResult.getFieldError().getDefaultMessage());
        }

        return resultUtil.success(Boolean.TRUE);
    }

    @GetMapping("test2")
    public void test2(HttpServletResponse response){
        Result<String> result = new Result<>();
        result.setCode(200);
        result.setData("test");
        try {
            response.getWriter().write(JSONObject.toJSONString(result));
        } catch (IOException e) {
//            e.printStackTrace();
            log.error("发生异常", e);
        }
    }

    @GetMapping("getGoods")
    public Result<Goods> getGoods(){
        ResultUtil<Goods> resultUtil = new ResultUtil<>();
        Goods goods = new Goods();
        goods.setName("java从入门到发疯");
//        goods.setTitle("java,book");
        goods.setPrice(null);
        goods.setCreateTime(new Date());
        return resultUtil.success(goods);
    }


}
